package cn.mengfly.testnrz.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class CompositeBufferTest {

    public static void main(String[] args) {
        CompositeByteBuf buf = ByteBufAllocator.DEFAULT.compositeBuffer();
        Charset charset = StandardCharsets.UTF_8;
        ByteBuf headBuf = Unpooled.copiedBuffer("消息头", charset);
        ByteBuf bodyBuf = Unpooled.copiedBuffer("消息体1", charset);

        buf.addComponents(headBuf, bodyBuf);
        sendMsg(buf);
        headBuf.retain();
        buf.release();

        bodyBuf = Unpooled.copiedBuffer("消息体2", charset);
        buf = ByteBufAllocator.DEFAULT.compositeBuffer();
        buf.addComponents(headBuf, bodyBuf);
        sendMsg(buf);
        buf.release();
    }

    private static void sendMsg(CompositeByteBuf buf) {
        for (ByteBuf byteBuf : buf) {
            int len = byteBuf.readableBytes();
            byte[] array = new byte[len];
            byteBuf.getBytes(byteBuf.readerIndex(), array);
            System.out.println(new String(array, StandardCharsets.UTF_8));
        }
    }
}
